package com.atguigu.springcloud.大批量任务处理.service;

import com.atguigu.springcloud.大批量任务处理.config.ThreadPoolConfig;
import com.atguigu.springcloud.大批量任务处理.util.TaskBatchSendUtil;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * @author XiongJianLin
 * @date Created in 2025/2/10 14:55
 */
@Service
public class CouponServiceImpl implements CouponService {

    @Resource
    private ThreadPoolTaskExecutor taskExecutor;
    /**
     * 下发优惠券
     *
     * @param couponNum
     */
    @Override
    public void batchTask(int couponNum) {
        List<String> couponList = new ArrayList<>(couponNum);
        for (int i = 0; i < couponNum; i++) {
            couponList.add("优惠券" + i);
        }

        // 用于确认全部下发优惠券完成
        CountDownLatch countDownLatch = new CountDownLatch(couponNum);

        long start = System.currentTimeMillis();
        try {
            // 优惠券逐条放入线程池
            for (String coupon : couponList) {
                taskExecutor.execute(() -> {
                    try {
                        // 模拟耗时
                        Thread.sleep(60);
                        System.out.println(String.format("[%s] 发送OK",coupon));
                    } catch (InterruptedException e) {
                        // 这里可以记录失败的下发 ， 用于重试之类的操作
                        e.printStackTrace();
                    }finally {
                        countDownLatch.countDown();
                    }
                });
            }
            countDownLatch.await();
        } catch (Exception e) {
            e.printStackTrace();
        }




        long end = System.currentTimeMillis();
        System.out.println("下发优惠券耗时：" + (end - start) + "ms");
    }

    @Override
    @SneakyThrows
    public void batchTaskV2(int couponNum) {
        List<String> couponList = getCouponList(couponNum);
        long start = System.currentTimeMillis();

        // 抽象工具方法。
        TaskBatchSendUtil.send(couponList, taskExecutor, TaskBatchSendUtil::disposeMailTask);
        long end = System.currentTimeMillis();
    }

    public List<String> getCouponList(int couponNum) {
        List<String> couponList = new ArrayList<>(couponNum);
        for (int i = 0; i < couponNum; i++) {
            couponList.add("优惠券" + i);
        }
        return couponList;
    }
}
